package com.xiezc.controller;


import com.xiaoleilu.hutool.cache.impl.TimedCache;
import com.xiezc.dao.FileInfoRepository;
import com.xiezc.dao.UserRepository;
import com.xiezc.dto.ExcepEnum;
import com.xiezc.entity.FileInfo;
import com.xiezc.dto.RespData;
import com.xiezc.entity.User;
import com.xiezc.util.XUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Administrator on 2017/5/19.df
 */
@RestController
@RequestMapping("fileInfo")
public class FileInfoAction {

    @Value("${filePath}")
    private String filePath;
    @Resource
    private TimedCache timedCache;
    @Resource
    private FileInfoRepository fileInfoRepository;

    @Resource
    private UserRepository userRepository;

    /**
     * 修改服务器中记录的同步文件路径
     *
     * @param newPath
     * @return
     */
    @RequestMapping(value = "/updatePath", method = RequestMethod.POST)
    public RespData updateTBPath(HttpServletRequest request, String newPath) {
        Assert.notNull(newPath, "请传入正确的参数");
        User user = (User) request.getAttribute("user");

        userRepository.updatePath(user.getId(),newPath);
        return RespData.success();
    }

    /**
     * 获得用户的所有文件的信息,用于客户端去比对
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findFileInfos", method = RequestMethod.POST)
    public RespData findFileInfo(HttpServletRequest request) {
        User user = (User) request.getAttribute("user");

        if (Objects.isNull(user)) {
            return RespData.fail(ExcepEnum.NotLogin);
        }

        List<FileInfo> fileInfoList = fileInfoRepository.findByUserId(user.getId());

        return RespData.success(fileInfoList);
    }

    /**
     * 上传新增的文件的信息, 不用上传了文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/addFileInfos", method = RequestMethod.POST)
    public RespData addFileInfo(HttpServletRequest request, @RequestBody FileInfo[] fileInfos) {
        User user = (User) request.getAttribute("user");
        if (Objects.isNull(user)) {
            return RespData.fail(ExcepEnum.NotLogin);
        }

        Stream<FileInfo> fStream = Stream.of(fileInfos);
        //挑选出服务器中没有的文件
        fStream = fStream.filter(f -> {
            List<FileInfo> list = fileInfoRepository.findByFileMd5(f.getFileMd5());
            if (list.isEmpty()) {
                return true;
            }
            return false;
        });
        List<FileInfo> list = fStream.collect(Collectors.toList());
        if (!list.isEmpty()) {
            //将这些文件存入定时缓存中
            timedCache.put(XUtil.WAIT_UP_FILE, list);
        }
        return RespData.success(list);
    }

    /**
     * 删除文件
     *
     * @return
     */
    @RequestMapping(value = "/deleteFileInfos", method = RequestMethod.POST)
    public Callable<RespData> deleteFile(HttpServletRequest request, @RequestBody FileInfo[] fileInfos) throws FileNotFoundException {
        return () -> {
            User user = (User) request.getAttribute("user");
            if (StringUtils.isEmpty(user)) {
                return RespData.fail(ExcepEnum.NotLogin);
            }

            Stream.of(fileInfos).forEach(fileInfo -> {
                fileInfoRepository.delete(fileInfo);
                if (fileInfoRepository.findByFileMd5(fileInfo.getFileMd5()).isEmpty()) {
                    Path path = Paths.get(filePath + user.getUserName() + File.separator + fileInfo.getFileMd5());
                    if (Files.exists(path)) {
                        path.toFile().delete();
                    }
                }
            });
            return RespData.success();
        };
    }


}
